const jwt = require("jsonwebtoken");
const { JWT_SECRET } = require("../config/config.default");
const { tokenExpiredError, invalidToken, hasNotAdminPermission } = require("../constant/err.type");
const auth = async (ctx, next) => {
    try {

        // 取得请求页面头部所带参数authorization
        const { authorization } = ctx.request.header;
        // authorization是以'Bearer '的字符串，去除'Bearer '
        if (authorization) {
            const token = authorization.replace("Bearer ", "");
            //console.log("页面携带的token:", token);
            //获取文件头中荷载信息payload{id ,user_name,is_admin}
            const payload = jwt.verify(token, JWT_SECRET);
            ctx.state.user = payload;
            // console.log(payload)
        } else {
            console.error('用户未登录，无token')
            ctx.body = {
                code: 0,
                message: '请登录后，再进行操作',
                result: ''
            }
            return
        }
    } catch (err) {
        switch (err.name) {
            case "TokenExpiredError":
                console.error("token过期");
                return ctx.app.emit("error", tokenExpiredError, ctx);
            case "JsonWebTokenError":
                console.error("无效的token");
                return ctx.app.emit("error", invalidToken, ctx);
            default:
                console.error("无效的token", err);
                return ctx.app.emit("error", invalidToken, ctx);
        }
    }

    await next();
};
const hadAdminPermission = async (ctx, next) => {
    const { is_admin } = ctx.state.user
    if (!is_admin) {
        console.error('该用户没有权限', ctx.state.user)
        return ctx.app.emit('error', hasNotAdminPermission, ctx)
    }
    await next()
}
module.exports = {
    auth,
    hadAdminPermission
};